import {
  getPickingTaskByPage,
  exportPickingTask,
  exportPickingDetails,
  getPickingDetailsByPageLike,
  getPickingTaskBySomething,
  pickingFinish,
  getBatchPlanByPage,
  allocation,
  scanSerNo,
  getMaterialPdfs,
  allocation2,
  allocation3,
} from '@/services/product/pickingTask';
import { getPickingDetailsByBatchPlanId, getPickingDetailsByPage } from '@/services/product/pickingDetails';
import { PlusOutlined, EditOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Input, message, Tabs, InputNumber, Tooltip } from 'antd';
import { sortTran, filterTranNew } from '@/utils/requestUtil';
import React, { useRef, useState } from 'react';
import type { tabType } from './components/interfaceProduct';
import PickingDetails from './pickingDetails';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import './pickingTask.less';
import { Ellipsis } from '@/components/Ellipsis';
import { element, number } from 'prop-types';
const PickingTask: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const actionRefUpperBefore = useRef<ActionType>();
  const actionRefBefore = useRef<ActionType>();
  const actionRefUpperAfter = useRef<ActionType>();
  const actionRefAfter = useRef<ActionType>();

  const actionRefBatchPlan = useRef<ActionType>();
  const actionRef1 = useRef<ActionType>();
  const detailRef = useRef(null);
  const [editingCell, setEditingCell] = useState(null); // 使用state跟踪编辑状态
  const [inputValue, setInputValue] = useState<number>();
  const [selections, setSelections] = useState([]);
  const [pickingTaskCode, setPickingTaskCode] = useState(0);
  const [findPickingValue, setFindPickingValue] = useState<string>();
  const ref = useRef(null);
  const inputRef = useRef(null);
  const [serialNumValue, setSerialNumValue] = useState('');
  const [pickingProjectName, setPickingProjectName] = useState('');
  const [woCode, setWoCode] = useState<string>('');
  const [pickingResponse, setPickingResponse] = useState(null);
  const [pickingRequest, setPickingRequest] = useState(null);
  const [materialList, setMaterialList] = useState();
  const [batchPlanId, setBatchPlanId] = useState(0);
  const refs1 = useRef(null);

  // 右上角的工单列表
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 30,
      align: 'center',
    },
    {
      title: '工单编号',
      align: 'center',
      dataIndex: 'wo',
      width: 60,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 50,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="scan"
          onClick={async () => {
            const result = await pickingFinish(record.id);
            if (result.code === 0) {
              actionRef.current?.reload();
              actionRefBefore.current?.reload();//未分物料中“分料任务查询”刷新
              actionRefUpperBefore.current?.reload();//未完成中“分料任务查询”刷新
              actionRef1.current?.reload();
              message.success('更新成功');
            }
          }}
        >
          分料
        </a>,
      ],
    },
  ];

  // 左上角的批次列表
  const columnsBatchPlan: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      width: 40,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      // valueType: 'select',      sorter:true,
      width: 80,
      align: 'center',
      sorter: true,
      // fieldProps: {
      //   options: ,
      // },
    },
    // {
    //   title: '当前批次',
    //   dataIndex: '',
    //   width: 60,
    //   align: 'center',
    //   sorter: false,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: `当前批次`,
      dataIndex: 'currentBatch',
      width: 50,
      search: false,
      align: 'center',
      sorter: true,
      render: (text, record) => (
        <>
          {text}/{record.batchCount}
        </>
      ),
    },
    {
      title: `批次交付日期`,
      dataIndex: 'batchDeliveryDate',
      width: 50,
      search: false,
      align: 'center',
      sorter: true,
    },
    {
      title: `分料计划结束日期`,
      dataIndex: 'productionSplit',
      width: 50,
      search: false,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      width: 60,
      align: 'center',
      sorter: false,
    },
    //
  ];

  const handleQtyChange = (record: any, value: any) => {
    setInputValue(Number(value));
  };

  const handleBlur = async (record: any) => {
    const temp: any = record;
    temp.outboundQty = inputValue;
    // const result = await updatePickingDetails(temp);
    // if (result && result.code == 0) {
    //   message.success(result.message);
    // }
    // setInputValue(0);
    setEditingCell(null);
  };

  // 其他三个tab页上方的批次+工单列表
  const columnsFinished: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '项目编号',
      align: 'center',
      sorter: true,
      dataIndex: 'projectCode',
      width: 150,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      width: 150,
    },
    {
      title: '当前批次编号',
      dataIndex: 'currentBatchCode',
      align: 'center',
      sorter: true,
      width: 150,
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,

      width: 180,
    },
    {
      title: '工单描述',
      dataIndex: 'woDesc',
      align: 'center',
      sorter: true,
      hideInTable: true, //后端API没有传数据
    },
    {
      title: '分料完成时间',
      dataIndex: 'pickingFinishTime',
      align: 'center',
      sorter: true,

      search: false,
      width: 120,
    },
    {
      title: '分料完成时间',
      dataIndex: 'pickingFinishTime',
      valueType: 'dateRange',
      hideInTable: true,
    },
    // {
    //   title: '任务状态',
    //   dataIndex: 'pickingState',
    //   align: 'center',
    //   sorter: true,
    //   search: false,
    //   width: 120,
    // },
    {
      title: '分料任务号',
      dataIndex: 'pickingTaskCode',
      align: 'center',
      sorter: true,
      width: 180,
    },
    {
      title: '计划完成时间',
      dataIndex: 'planFinishTime',
      align: 'center',
      sorter: true,

      search: false,
      width: 120,
    },
    {
      title: '计划完成时间',
      dataIndex: 'planFinishTime',
      valueType: 'dateRange',

      hideInTable: true,
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      align: 'center',
      sorter: true,

      width: 180,
    },
    {
      title: '柜体类型编号',
      align: 'center',
      sorter: true,
      dataIndex: 'productType',
      hideInTable: true,
      width: 120,
    },
    {
      title: '柜体类型',
      align: 'center',
      sorter: true,

      dataIndex: 'productTypeName',
      width: 120,
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      width: 180,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      dataIndex: 'createName',
      width: 120,
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp: string[] = [];
      const tempCodeOlny: string[] = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push({
            id: item.id,
            materialCode: item.materialCode,
            materialSpec: item.materialSpec,
            materialName: item.materialName,
          });
          tempCodeOlny.push(item.id);
        });
      }
      setSelections(temp);
    },
  };

  // 快速分料
  const findPickingDetails = async () => {
    let index = materialList.findIndex((element) => element.materialCode === findPickingValue);
    if(index === -1){
      message.error('请输入正确的物料编号');
      return;
    }
    let temp = materialList[index];
    temp.thistimeQty = temp.thistimeQty + temp.notIssuedQty; //本次数量等于本次数量加上未分数量
    temp.notIssuedQty = 0; //未分数量变为0
    temp.outboundQty = temp.materialQty; //已分数量直接等于需求数量
    console.log(temp);
    if(pickingTaskCode !== 0) { //按工单
      const result = await allocation2(temp);
      console.log(result, '分料结果');
      if (result.code === 0) {
        setMaterialList(materialList.map(item => {
          if(item.id === temp.id){
            return temp;
          } else {
            return item;
          }
        }));
        message.success('分料成功');
      }
      else {
        setMaterialList(materialList);
        message.error('分料失败');
      }
    } else { //按批次
      let temp2 = {
        materialCode: temp.materialCode,
        notIssuedQty: temp.notIssuedQty,
        outboundQty: temp.outboundQty,
        batchPlanId: batchPlanId,
      };
      console.log(temp2,'发的数据')
      const result = await allocation3(temp2);
      console.log(result, '分料结果3');
      if (result.code === 0) {
        setMaterialList(materialList.map(item => {
          if(item.id === temp.id){
            return temp;
          } else {
            return item;
          }
        }));
        message.success('分料成功');
      }
      else {
        setMaterialList(materialList);
        message.error('分料失败');
      }
    }
  };

  React.useEffect(() => {
    setInputValue(Number(inputValue));
  }, [inputValue]);

  // 修改本次数量后分料
  const handleAllocation = async (record: any) => {
    const beforeRecord = record;
    let temp = record;
    let delta = inputValue - record.thistimeQty;
    if (delta > record.notIssuedQty) {
      message.error('本次数量的变化值不能大于未分数量')
      return;
    }
    temp.outboundQty = record.outboundQty + delta;
    temp.notIssuedQty = record.materialQty - record.outboundQty;
    temp.thistimeQty = inputValue;
    if(pickingTaskCode !== 0) { //按工单
      const result = await allocation2(temp);
      console.log(result, '分料结果');
      if (result.code === 0) {
        let newMaterilList = materialList;
        let editIndex = newMaterilList.find((element) => element.id === temp.id);
        newMaterilList[editIndex] = temp;
        setMaterialList(newMaterilList);
        setEditingCell(null);
        message.success('分料成功');
      }
      else {
        setEditingCell(null);
        message.error('分料失败');
      }
    } else { //按批次
      let temp = {
        materialCode: record.materialCode,
        notIssuedQty: record.notIssuedQty,
        outboundQty: record.outboundQty,
        batchPlanId: batchPlanId,
      };
      console.log(temp,'发的数据')
      const result = await allocation3(temp);
      console.log(result, '分料结果3');
      if (result.code === 0) {
        setEditingCell(null);
        message.success('分料成功');
      }
      else {
        record = temp;
        setEditingCell(null);
        message.error('分料失败');
      }
    }
  }

  // tab1下方的物料列表
  const columns1: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      align: 'center',
      sorter: true,
      width: 100,
      copyable: true,
    },
    {
      title: '物料名称',
      align: 'center',
      sorter: true,
      dataIndex: 'materialName',

      width: 100,
    },
    {
      title: '物料规格',
      align: 'center',
      sorter: true,
      dataIndex: 'materialSpec',
      width: 100,
    },
    {
      title: '是否变更',
      align: 'center',
      sorter: true,
      dataIndex: 'isChanged',
      render: (text) => {
        return text == 0 ? '否' : '是';
      },
      width: 60,
    },
    {
      title: '单位',
      align: 'center',
      sorter: true,
      dataIndex: 'unit',
      width: 60,
    },
    {
      title: '产品编号',
      align: 'center',
      sorter: true,
      dataIndex: 'partCode',
      hideInTable: true,
      width: 100,
    },
    {
      title: '位置号',
      align: 'center',
      sorter: true,
      dataIndex: 'positionNo',
      width: 60,
    },
    {
      title: '需求数量',
      align: 'center',
      sorter: true,
      dataIndex: 'materialQty',
      width: 60,
    },
    {
      title: '本次数量',
      align: 'center',
      sorter: true,
      dataIndex: 'thistimeQty',
      width: 80,
      render: (text, record) => {
        if (editingCell === record.id) {
          // 编辑状态下显示InputNumber
          return (
            <InputNumber
              value={record.thistimeQty}
              min={0}
              step={1} // 设置步进值为1
              onChange={(value) => setInputValue(Number(value))}
              onBlur={() => setEditingCell(null)} // 失去焦点时取消编辑状态
              // onPressEnter={() => setEditingCell(null)} // 按下回车键时取消编辑状态
              onPressEnter={() => handleAllocation(record)}
              autoFocus // 自动获取焦点
            />
          );
        } else {
          return (
            <span
              style={{ cursor: 'pointer' }}
              onClick={() => setEditingCell(record.id)} // 点击时设置编辑状态
            >
              {text}
              <EditOutlined style={{ color: 'green' }} />
            </span>
          );
        }
      },
    },
    {
      title: '未分数量',
      align: 'center',
      sorter: true,
      dataIndex: 'notIssuedQty',
      width: 60,
      render: (text, record) => {
        // if (editingCell === record.id) {
        //   return notQty !== -1 ? notQty : 0;
        // } else {
        //   return text;
        // }
        return text;
        // return notQty !== -1 ? notQty : text;
      },
    },
    {
      title: '已分数量',
      align: 'center',
      sorter: true,
      dataIndex: 'outboundQty',
      width: 60,
      render: (text, record) => {
        return text;
        /*         if (editingCell === record.id) {
                  // 编辑状态下显示InputNumber
                  return (
                    <InputNumber
                      value={record.outboundQty}
                      min={0}
                      step={1} // 设置步进值为1
                      onChange={(value) => handleQtyChange(record, value)}
                      onBlur={() => setEditingCell(null)} // 失去焦点时取消编辑状态
                      // onPressEnter={() => setEditingCell(null)} // 按下回车键时取消编辑状态
                      onPressEnter={async () => {
                        const temp: any = record;
                        temp.outboundQty = inputValue;
                        if (temp.outboundQty === '') {
                          //数量不为空才提交
                          message.error('未输入已发数量');
                        } else if (temp.outboundQty % 1 != 0) {
                          message.error('已发数量必须为整数');
                        } else {
                          const result = await allocation(temp);
                          if (result?.code == 0) {
                            message.success('分料成功');
                            setEditingCell(null);
                          }
                          actionRef1.current!.reload();
                        }
                      }}
                      autoFocus // 自动获取焦点
                    />
                  );
                } else {
                  return (
                    <span
                      style={{ cursor: 'pointer' }}
                      onClick={() => setEditingCell(record.id)} // 点击时设置编辑状态
                    >
                      {text}
                      <EditOutlined style={{ color: 'green' }} />
                    </span>
                  );
                } */
      },
    },
    {
      title: '物料分类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialClassification',
      width: 80,
    },
    {
      title: '物料种类',
      align: 'center',
      sorter: true,
      dataIndex: 'materialType',
      width: 80,
    },
    {
      title: '是否甲供',
      align: 'center',
      sorter: true,
      dataIndex: 'isJia',
      width: 80,
    },
    {
      title: '序列号',
      width: 100,
      align: 'center',
      sorter: true,
      dataIndex: 'serialNum',
      render: (text, record) => {
        // 编辑状态下显示Input框框
        return (
          <Input
            ref={inputRef}
            onChange={(e) => {
              setSerialNumValue(e.target.value);
            }}
            onBlur={async (e) => {
              const temp: any = record;
              temp.serialNum = serialNumValue;
              if (temp.serialNum === '') {
                //序列号不为空才提交
                message.error('未输入序列号');
              } else {
                const result = await scanSerNo(temp);
                if (result?.code == 0) {
                  message.success('扫描序列号成功');
                }
                setSerialNumValue(''); //重置序列号值为空
                actionRef1.current!.reload();
              }
            }}
            onPressEnter={async () => {
              const temp: any = record;
              temp.serialNum = serialNumValue;
              if (temp.serialNum === '') {
                //序列号不为空才提交
                message.error('未输入序列号');
              } else {
                const result = await scanSerNo(temp);
                if (result?.code == 0) {
                  message.success('扫描序列号成功');
                }
                setSerialNumValue(''); //重置序列号值为空
                actionRef1.current!.reload();
              }
            }}
          />
        );
      },
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,
      width: 100,

      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      width: 60,
      align: 'center',
      sorter: true,

      dataIndex: 'createName',
    },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   key: 'option',
    //   width: 120,
    //  align: 'center',sorter: true,
    //   fixed: 'right',
    //   render: (text, record, _, action) => [
    //     <a
    //       key="scan"
    //       onClick={async () => {
    //         const result = await addMaterialQty({
    //           materialCode: record.materialCode,
    //           pickingTaskCode: record.pickingTaskCode,
    //         });
    //         if (result && result.code === 0) {
    //           message.success(result.message);
    //         }
    //         actionRef1.current?.reload();
    //       }}
    //     >
    //       扫描
    //     </a>,
    //   ],
    // },
  ];

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '未完成',
      content: (
        <div>
          <div className="top">
            <div className="left">
              <ProTable
                headerTitle="批次计划"
                actionRef={actionRefBatchPlan} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                // formRef={refs}
                onRow={(record) => ({
                  onClick: (a) => {
                    setWoCode(record.batchPlanCode); //用于触发右侧的表格
                    setBatchPlanId(record.id); //用于触发最下方的表格
                    setPickingTaskCode(0);
                    setMaterialList([]);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRefUpperBefore.current!.reload(); //刷新右侧表格
                    actionRef1.current!.reload(); //刷新最下方的表格
                  },
                })}
                request={async (params = {}, sort, filter) => {
                  const res = { ...params };
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(res);
                  const result = await getBatchPlanByPage({
                    ...params,
                    current: 1,
                    pageSize: 5000,
                    sorters: sorters,
                    filters: filters,
                  });
                  const temp = result.data.content.filter(
                    (item: any) => item && item.state !== 0,
                  );
                  setWoCode(temp[0] && temp[0].projectCode);
                  actionRefUpperBefore.current!.reload();
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columnsBatchPlan}
                scroll={{ x: 800, y: 280 }}
              />
            </div>
            <div className="right">
              <ProTable
                search={{
                  labelWidth: 'auto',
                  span: 12, // 控制搜索框宽度, 一行搜索框的个数 = 24 / span
                }}
                onRow={(record) => ({
                  onClick: (a) => {
                    setPickingProjectName(record.projectName);
                    setPickingTaskCode(record.pickingTaskCode);
                    a.stopPropagation();
                    console.log(a, 'a');
                    let s = a.target.parentNode.parentNode.children;
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRef1.current!.reload();
                  },
                })}
                headerTitle="分料任务查询"
                actionRef={actionRefUpperBefore} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                formRef={ref}
                // toolBarRender={(action, { selectedRows }) => [
                //   <Button
                //     key="button"
                //     icon={<PlusOutlined />}
                //     onClick={() => {
                //       const filters = filterTranNew(ref.current!.getFieldsValue());
                //       exportPickingTask({
                //         current: 1,
                //         pageSize: 5000,
                //         filters: filters,
                //       }).then((res) => {
                //         const aLink = document.createElement('a');
                //         document.body.appendChild(aLink);
                //         aLink.style.display = 'none';
                //         aLink.href = window.URL.createObjectURL(res);
                //         aLink.setAttribute('download', `PickingTask.xls`);
                //         aLink.click();
                //         document.body.removeChild(aLink);
                //       });
                //     }}
                //     type="primary"
                //   >
                //     导出
                //   </Button>,
                // ]}
                request={async (params = {}, sort) => {
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(params);
                  const result = await getPickingTaskByPage({
                    ...params,
                    sorters: sorters,
                    filters: filters,
                  });
                  let temp;
                  if (woCode) {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '未分料' && item.batchPlanCode === woCode;
                    });
                  } else {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '未分料' && item.wo === 'IMPOISSBLE';
                    });
                  }
                  if (pickingResponse) {
                    temp = pickingResponse;
                  }
                  setPickingRequest(temp);
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columns}
                scroll={{ x: 400, y: 295 }}
              />
            </div>
          </div>

          <div className="center">
            <Input
              value={findPickingValue}
              onChange={(e) => {
                setFindPickingValue(e.target.value);
              }}
              placeholder="请输入物料代码/规格"
              size="large"
              style={{ width: '220px' }}
            />
            <Button
              type="primary"
              size="large"
              onClick={() => findPickingDetails()}
            >
              快速分料
            </Button>
            {/*             <Button
              style={{ marginLeft: '20px' }}
              size="large"
              onClick={() => {
                setFindPickingValue('');
                findPickingDetails();
              }}
            >
              重置
            </Button> */}
            <Button
              type="primary"
              onClick={async (e) => {
                if (selections.length === 0) {
                  message.info('请先选择要打印的物料');
                } else {
                  const temp = new Array(); //API只需要id，因此将id放到一个数组中
                  selections.map((item) => {
                    temp.push(item.id);
                  });
                  console.log(temp);
                  const res = await getMaterialPdfs(temp);
                  console.log(res);
                  const iframe = document.createElement('iframe'); //通过iframe进行打印机打印
                  iframe.style.display = 'none';
                  iframe.src = window.URL.createObjectURL(res);
                  document.body.appendChild(iframe);
                  iframe.contentWindow?.focus();
                  iframe.contentWindow?.print();
                  /* selections.map(async (item) => {
    await getBatchBarcodesByPickingTaskCode(item).then((res) => {
      const aLink = document.createElement('a');
      document.body.appendChild(aLink);
      aLink.style.display = 'none';
      aLink.href = window.URL.createObjectURL(res);
      const filename = item.materialName + '.png';
      aLink.setAttribute('download', `${filename}`);
      aLink.click();
      document.body.removeChild(aLink);
    });
  });
} */
                  actionRef1.current!.reload();
                  /*               setTimeout(() => {
                                  setSelections([]);
                                }, 1000);
                                getBatchBarcodesByPickingTaskCode(pickingTaskCode).then((res) => {
                                  const aLink = document.createElement('a');
                                  document.body.appendChild(aLink);
                                  aLink.style.display = 'none';
                                  aLink.href = window.URL.createObjectURL(res);
                                  const filename = '111' + '条码.png';
                                  aLink.setAttribute('download', `${filename}`);
                                  aLink.click();
                                  document.body.removeChild(aLink);
                                }); */
                }
              }}
              size="large"
              style={{ marginLeft: '20px' }}
            >
              物料打印
          </Button>
          </div>
          <div className="bottom">
            <ProTable
              actionRef={actionRef1} //用于触发刷新操作等，看api
              rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
              search={false}
              formRef={refs1}
              value={materialList}
              rowSelection={{
                selections,
                ...rowSelection,
              }}
              toolBarRender={(action, { selectedRows }) => [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // const filters = filterTranNew();
                    exportPickingDetails({
                      current: 1,
                      pageSize: 5000,
                      filters: filterTranNew,
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `PickingTaskDetails.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,
              ]}
              request={async (params = {}, sort, filter) => {
                let result;
                if (batchPlanId !== 0) {
                  if (pickingTaskCode !== 0) {
                    const sorters = sortTran(sort);
                    const filters = [
                      {
                        andOr: 'and',
                        field: 'pickingTaskCode',
                        operator: 'eq',
                        value: pickingTaskCode,
                      },
                    ];
                    result = await getPickingDetailsByPage({
                      ...params,
                      sorters: sorters,
                      filters: filters,
                    });
                    setPickingResponse(null);
                    console.log(result,'result');
                    setMaterialList(result.data.content);
                    return {
                      data: result.data.content,
                      total: result.data.totalElements,
                      success: result.success,
                    };
                  }
                  else {
                    let result = await getPickingDetailsByBatchPlanId(batchPlanId);
                    let index = 1;
                    result.data.map(r => {
                      r.id = index++;
                    })
                    setMaterialList(result.data);
                    return {
                      data: result.data,
                      total: result.data.length,
                      success: result.message,
                    };
                  }
                }
              }}
              columns={columns1}
              scroll={{ x: 2100, y: 350 }}
            />
          </div>
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '未分物料',
      content: (
        <div>
          <div className="top">
            <div className="left">
              <ProTable
                headerTitle="批次计划"
                actionRef={actionRefBatchPlan} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                // formRef={refs}
                onRow={(record) => ({
                  onClick: (a) => {
                    console.log('ss未分物料', record.batchPlanCode);
                    setWoCode(record.batchPlanCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRefBefore.current!.reload();
                  },
                })}
                request={async (params = {}, sort, filter) => {
                  const res = { ...params };
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(res);
                  const result = await getBatchPlanByPage({
                    ...params,
                    current: 1,
                    pageSize: 5000,
                    sorters: sorters,
                    filters: filters,
                  });
                  const temp = result.data.content.filter(
                    (item: any) => item && item.state !== 0,
                  );
                  setWoCode(temp[0] && temp[0].projectCode);
                  actionRefBefore.current!.reload();
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columnsBatchPlan}
                scroll={{ x: 800, y: 280 }}
              />
            </div>
            <div className="right">
              <ProTable
                search={{
                  labelWidth: 'auto',
                  span: 12, // 控制搜索框宽度, 一行搜索框的个数 = 24 / span
                }}
                onRow={(record) => ({
                  onClick: (a) => {
                    setPickingProjectName(record.projectName);
                    setPickingTaskCode(record.pickingTaskCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRef1.current!.reload();
                  },
                })}
                headerTitle="分料任务查询"
                actionRef={actionRefBefore} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                formRef={ref}
                // toolBarRender={(action, { selectedRows }) => [
                //   <Button
                //     key="button"
                //     icon={<PlusOutlined />}
                //     onClick={() => {
                //       const filters = filterTranNew(ref.current!.getFieldsValue());
                //       exportPickingTask({
                //         current: 1,
                //         pageSize: 5000,
                //         filters: filters,
                //       }).then((res) => {
                //         const aLink = document.createElement('a');
                //         document.body.appendChild(aLink);
                //         aLink.style.display = 'none';
                //         aLink.href = window.URL.createObjectURL(res);
                //         aLink.setAttribute('download', `PickingTask.xls`);
                //         aLink.click();
                //         document.body.removeChild(aLink);
                //       });
                //     }}
                //     type="primary"
                //   >
                //     导出
                //   </Button>,
                // ]}
                request={async (params = {}, sort) => {
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(params);
                  const result = await getPickingTaskByPage({
                    ...params,
                    sorters: sorters,
                    filters: filters,
                  });
                  let temp; 
                  if (woCode) {
                    temp = result.data.content.filter((item: any) => {
                      return (
                        (item.pickingState === '未领物料' || item.pickingState === '车间接收') &&
                        item.batchPlanCode === woCode
                      );
                    });
                  } else {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '未领物料' && item.wo === 'IMPOISSBLE';
                    });
                  }
                  if (pickingResponse) {
                    temp = pickingResponse;
                  }
                  setPickingRequest(temp);
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columns}
                scroll={{ x: 400, y: 295 }}
              />
            </div>
          </div>

          <div className="center">
            <Input
              value={findPickingValue}
              onChange={(e) => {
                setFindPickingValue(e.target.value);
              }}
              placeholder="请输入物料代码/规格"
              size="large"
              style={{ width: '220px' }}
            />
            <Button
              type="primary"
              size="large"
              onClick={() => findPickingDetails()}
            >
              快速分料
            </Button>
            {/*             <Button
              style={{ marginLeft: '20px' }}
              size="large"
              onClick={() => {
                setFindPickingValue('');
                findPickingDetails();
              }}
            >
              重置
            </Button> */}
          </div>
          <div className="bottom">
            {/* <PickingDetails state={1} pickingTaskCode={pickingTaskCode} ref={detailRef} /> */}

            <ProTable
              actionRef={actionRef1} //用于触发刷新操作等，看api
              rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
              search={false}
              formRef={refs1}
              rowSelection={{
                selections,
                ...rowSelection,
              }}
              onRow={() => ({
                onClick: (a) => {
                  a.stopPropagation();
                  console.log(a, 'a');
                  let s = a.target.parentNode.parentNode.children;
                  console.log(s);
                  // 先重置为默认样式
                  for (var i = 0; i < s.length; i++) {
                    s[i].style.color = '#000000d9';
                    s[i].style.fontWeight = 'normal';
                    s[i].style.backgroundColor = '#fff';
                  }
                  // 再设置高亮样式
                  a.target.parentNode.style.color = '#13C2C2';
                  a.target.parentNode.style.fontWeight = 'bold';
                  a.target.parentNode.style.backgroundColor = '#e6fffb';
                },
              })}
              toolBarRender={(action, { selectedRows }) => [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // const filters = filterTranNew();
                    exportPickingDetails({
                      current: 1,
                      pageSize: 5000,
                      filters: filterTranNew,
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `PickingTaskDetails.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,
              ]}
              request={async (params = {}, sort, filter) => {
                let result;
                let temp;
                if (findPickingValue && pickingTaskCode) {
                  const data = {
                    pickingTasks: pickingRequest,
                    s: findPickingValue,
                  };
                  result = await getPickingTaskBySomething(data);
                  temp = result.data.content;
                  setPickingResponse(result.data.content);
                }
                const sorters = sortTran(sort);
                const filters = [
                  {
                    andOr: 'and',
                    field: 'pickingTaskCode',
                    operator: 'eq',
                    value: pickingTaskCode,
                  },
                ];
                const res = await getPickingDetailsByPage({
                  current: 1,
                  pageSize: 5000,
                  sorters: sorters,
                  filters: filters,
                });
                temp = res.data.content.filter((item: any) => item.notIssuedQty != 0);
                setPickingResponse(null);
                temp.map((r) => {
                  r.projectName = pickingProjectName;
                }); //将每一个查询出来的项 补充上项目名称
                return {
                  data: temp,
                  total: temp.length,
                  success: res.message,
                };
              }}
              columns={columns1}
              scroll={{ x: 2100, y: 350 }}
            />
          </div>
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '已分物料',
      content: (
        <div>
          <div className="top">
            <div className="left">
              <ProTable
                headerTitle="批次计划"
                actionRef={actionRefBatchPlan} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                // formRef={refs}
                onRow={(record) => ({
                  onClick: (a) => {
                    setWoCode(record.batchPlanCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRefUpperAfter.current!.reload();
                  },
                })}
                request={async (params = {}, sort, filter) => {
                  const res = { ...params };
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(res);
                  const result = await getBatchPlanByPage({
                    ...params,
                    current: 1,
                    pageSize: 5000,
                    sorters: sorters,
                    filters: filters,
                  });
                  const temp = result.data.content.filter(
                    (item: any) => item && item.state !== 0,
                  );
                  setWoCode(temp[0] && temp[0].projectCode);
                  actionRefUpperAfter.current!.reload();
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columnsBatchPlan}
                scroll={{ x: 800, y: 280 }}
              />
            </div>
            <div className="right">
              <ProTable
                search={{
                  labelWidth: 'auto',
                  span: 12, // 控制搜索框宽度, 一行搜索框的个数 = 24 / span
                }}
                onRow={(record) => ({
                  onClick: (a) => {
                    setPickingTaskCode(record.pickingTaskCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                  },
                })}
                headerTitle="分料任务查询"
                actionRef={actionRefUpperAfter} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                formRef={ref}
                request={async (params = {}, sort) => {
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(params);
                  const result = await getPickingTaskByPage({
                    ...params,
                    sorters: sorters,
                    filters: filters,
                  });
                  let temp;
                  if (woCode) {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '未领物料' && item.batchPlanCode === woCode;
                    });
                  } else {
                    temp = result.data.content.filter((item: any) => {
                      return (
                        item.pickingState === '未领物料' && item.batchPlanCode === 'IMPODDIBLE'
                      );
                    });
                  }
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columns.filter(function (item) {
                  return item.valueType != 'option';
                })}
                scroll={{ x: 400, y: 295 }}
              />
            </div>
          </div>
          <div className="bottom">
            <PickingDetails
              state={2}
              // finishCode={true}
              pickingTaskCode={pickingTaskCode}
              ref={detailRef}
            />
          </div>
        </div>
      ),
    },
    {
      name: 'tab4',
      label: '已完成',
      content: (
        <div>
          <div className="top">
            <div className="left">
              <ProTable
                headerTitle="批次计划"
                actionRef={actionRefBatchPlan} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                // formRef={refs}
                onRow={(record) => ({
                  onClick: (a) => {
                    console.log('ss已完成', record.batchPlanCode);
                    setWoCode(record.batchPlanCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // actionRef.current?.reload();
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                    actionRefAfter.current!.reload();
                  },
                })}
                request={async (params = {}, sort, filter) => {
                  const res = { ...params };
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(res);
                  const result = await getBatchPlanByPage({
                    ...params,
                    current: 1,
                    pageSize: 5000,
                    sorters: sorters,
                    filters: filters,
                  });
                  const temp = result.data.content.filter(
                    (item: any) => item && item.state !== 0,
                  );
                  setWoCode(temp[0] && temp[0].projectCode);
                  actionRefAfter.current!.reload();
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columnsBatchPlan}
                scroll={{ x: 800, y: 280 }}
              />
            </div>
            <div className="right">
              <ProTable
                search={{
                  labelWidth: 'auto',
                  span: 12, // 控制搜索框宽度, 一行搜索框的个数 = 24 / span
                }}
                onRow={(record) => ({
                  onClick: (a) => {
                    setPickingTaskCode(record.pickingTaskCode);
                    a.stopPropagation();
                    let s = a.target.parentNode.parentNode.children;
                    console.log(s);
                    // 先重置为默认样式
                    for (var i = 0; i < s.length; i++) {
                      s[i].style.color = '#000000d9';
                      s[i].style.fontWeight = 'normal';
                      s[i].style.backgroundColor = '#fff';
                    }
                    // 再设置高亮样式
                    a.target.parentNode.style.color = '#13C2C2';
                    a.target.parentNode.style.fontWeight = 'bold';
                    a.target.parentNode.style.backgroundColor = '#e6fffb';
                  },
                })}
                headerTitle="分料任务查询"
                actionRef={actionRefAfter} //用于触发刷新操作等，看api
                rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
                formRef={ref}
                request={async (params = {}, sort) => {
                  const sorters = sortTran(sort);
                  const filters = filterTranNew(params);
                  const result = await getPickingTaskByPage({
                    ...params,
                    sorters: sorters,
                    filters: filters,
                  });
                  console.log(woCode, 'woCodewoCodewoCodewoCode');
                  let temp;
                  if (woCode) {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '已分料' && item.batchPlanCode === woCode;
                    });
                  } else {
                    temp = result.data.content.filter((item: any) => {
                      return item.pickingState === '已分料' && item.wo === 'IMPOISSBLE';
                    });
                  }
                  return {
                    data: temp,
                    total: temp.length,
                    success: result.success,
                  };
                }}
                columns={columns.filter(function (item) {
                  return item.valueType != 'option';
                })}
                scroll={{ x: 400, y: 295 }}
              />
            </div>
          </div>
          <div className="bottom">
            <PickingDetails state={3} pickingTaskCode={pickingTaskCode} ref={detailRef} />
          </div>
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        onTabClick={() => {
          setPickingTaskCode(undefined);
          setFindPickingValue('');
          setWoCode('');
        }}
        type="card"
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
    </PageHeaderWrapper>
  );
};
export default PickingTask;
